#include "Photo.h"
#include <string>

SDL_Surface* Photo::mpPhotoBorderSurface = NULL;

Photo::Photo()
{
  // TODO: this comes from the example in the SDL docs, but this stuff should be defined for the game and referenced here
  /* Create a 32-bit surface with the bytes of each pixel in R,G,B,A order,
  as expected by OpenGL for textures */
  Uint32 rmask, gmask, bmask, amask;

    /* SDL interprets each pixel as a 32-bit number, so our masks must depend
  on the endianness (byte order) of the machine */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
  rmask = 0xff000000;
  gmask = 0x00ff0000;
  bmask = 0x0000ff00;
  amask = 0x000000ff;
#else
  rmask = 0x000000ff;
  gmask = 0x0000ff00;
  bmask = 0x00ff0000;
  amask = 0xff000000;
#endif

  mpPhotoSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, PHOTO_SIZE_X, PHOTO_SIZE_Y, 32,
                                 rmask, gmask, bmask, amask);
  if(mpPhotoSurface == NULL) {
    fprintf(stderr, "Photo error: CreateRGBSurface failed: %s\n", SDL_GetError());
    exit(4001);
  }
}

void Photo::SetBorder(string imageFilename) {
  if (mpPhotoBorderSurface) {
     SDL_FreeSurface(mpPhotoBorderSurface);
     mpPhotoBorderSurface = NULL;
  }
  mpPhotoBorderSurface = IMG_Load(imageFilename.c_str());
  if (!mpPhotoBorderSurface) {
    cerr << "Photo error: can't load " << imageFilename << " as photo border" << endl;
    exit(4004);
  }
}

// has to be called before exit to free resources
void Photo::ClearBorder() {
  if (mpPhotoBorderSurface) {
     SDL_FreeSurface(mpPhotoBorderSurface);
     mpPhotoBorderSurface = NULL;
  }
}

int Photo::Shoot(SDL_Surface *src, int x, int y) {
  int nResult = 0;
  if (!src) {
    cerr << "Photo error: invalid destination surface" << endl;
    exit(4002);
  }
  if (!mpPhotoSurface) {
    cerr << "Photo error: Photo not initialized" << endl;
    exit(4003);
  }
  SDL_Rect srcRect;
  srcRect.x = x;
  srcRect.y = y;
  srcRect.w = PHOTO_SIZE_X;
  srcRect.h = PHOTO_SIZE_Y;
  nResult = SDL_BlitSurface(src, &srcRect, mpPhotoSurface, NULL);
  return nResult;
}

int Photo::Draw(SDL_Surface *dst, int x, int y) {
  int nResult = 0;
  if (!dst)
    cerr << "Photo error: invalid destination surface" << endl;
  if (!mpPhotoSurface)
    cerr << "Photo error: Photo not initialized" << endl;
  SDL_Rect dstRect;
  dstRect.x = x + PHOTO_BORDER_TOP_LEFT_X;
  dstRect.y = y + PHOTO_BORDER_TOP_LEFT_Y;
  dstRect.w = PHOTO_SIZE_X; // ignored by blit
  dstRect.h = PHOTO_SIZE_Y; // ignored by blit
  nResult = SDL_BlitSurface(mpPhotoSurface, NULL, dst, &dstRect);
  if (!nResult && mpPhotoBorderSurface) {
    nResult = SDL_BlitSurface(mpPhotoBorderSurface, NULL, dst, &dstRect);
  }
  return nResult;
}

Photo::~Photo() {
  if (mpPhotoSurface) {
    SDL_FreeSurface(mpPhotoSurface);
    mpPhotoSurface = NULL;
  }
}
